package org.example.controller;

import org.example.entity.Person;
import org.springframework.core.task.TaskExecutor;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @description:
 * @author: yh
 * @date: 2022/12/13
 */
@RestController
@RequestMapping("/test")
public class TestController {

    @Resource
    private TaskExecutor taskExecutor;
    /**
     * 批次执行线程大小
     */
     private int threadNum = 10;

    @GetMapping(value = "/importData")
    public String importData(){
        List<Person> personList = initData();
        if (CollectionUtils.isEmpty(personList)) {
            return "ok";
        }
        long startTime = System.currentTimeMillis();
        AtomicInteger atomicInteger = new AtomicInteger(1);
        // 定义栅栏
        CyclicBarrier cyclicBarrier = new CyclicBarrier(10, () -> {
            System.out.println("第几次：" + atomicInteger.getAndIncrement());
        });
        List<Person> successList = new ArrayList<>();
        List<Person> errorList = new ArrayList<>();

        // 循环次数
        int forNumber = personList.size() % threadNum == 0 ? personList.size() / threadNum : (personList.size() / threadNum) + 1;

        AtomicInteger listIndex = new AtomicInteger();
        for (int i = 0; i < threadNum; i++) {
            taskExecutor.execute(() -> {
                for (int j = 0; j < forNumber; j++) {
                    if (listIndex.get() > personList.size() - 1) {
                        try {
                            System.out.println(listIndex.getAndIncrement());
                            cyclicBarrier.await();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        continue;
                    }
                    Person person = personList.get(listIndex.get());
                    boolean state = importData(person);
                    if(state){
                        successList.add(person);
                    } else{
                        errorList.add(person);
                    }
                    try {
                        cyclicBarrier.await();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    System.out.println(listIndex.getAndIncrement());
                }
            });
        }
        while (true){
            if (listIndex.get() == (forNumber * threadNum) -1) {
                long endTime = System.currentTimeMillis();
                System.out.println("总耗时" + (endTime - startTime));
                break;
            }
        }
        System.out.println(successList.size());
        System.out.println(errorList.size());

        return "ok";
    }


    /**
     * 模拟导入数据库
     * @param person 处理的对象
     * @return 是否成功
     */
    private boolean importData(Person person) {
        // 模拟处理耗时，20-29ms随机数
        int expend = (int) (Math.random() * 10) + 20;
        try {
            TimeUnit.MILLISECONDS.sleep(expend);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 性别为女的处理成功
        if ("女".equals(person.getGender())) {
            return true;
        }
        return false;
    }
    /**
     * 获取初始化数据
     * @author: yh
     * @date: 2022/12/13
     * @return List<Person>
     */
    private List<Person> initData() {
        List<Person> list = new ArrayList<>();
        for (int i = 1; i <= 2001; i++) {
            Person obj = new Person();
            obj.setId(i);
            obj.setGender(i % 2 == 0 ? "男" : "女");
            obj.setName("老王-" + i);
            list.add(obj);
        }
        return list;
    }
}
